package com.zzyk.microCloud.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.zzyk.main.configuration.exception.UserException;
import com.zzyk.main.model.pojo.SysUser;
import com.zzyk.main.model.vo.Message;
import com.zzyk.main.model.vo.UserInfo;
import com.zzyk.main.model.vo.WxUser;
import com.zzyk.main.service.IMsgService;
import com.zzyk.main.service.ISysUserService;
import com.zzyk.main.utils.MD5Utils;
import com.zzyk.main.utils.TencentAppUtils;
import org.apache.http.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/api/sys")
public class ApiController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IMsgService msgService;

    @RequestMapping("login")
    public Message login(SysUser sysUser, @RequestParam("jsCode") String jsCode) throws HttpException, UserException {
        try {
            String result = TencentAppUtils.code2Session(jsCode);
            Map map = (Map) JSONObject.parse(result);
            String openId = (String) map.get("openid");
            String sessionKey = (String) map.get("session_key");
            if (openId == null) {
                throw new UserException("jsCode无效");
            } else {
                System.out.println(openId);
            }
            UserInfo user = null;
            if (sysUser != null && sysUser.getUsername() != null) {
                user = sysUserService.apiLogin(sysUser);
                sysUserService.delWxUserByOpenId(openId);
                WxUser wxUser = new WxUser();
                wxUser.setUserId(user.getId());
                wxUser.setWxOpenId(openId);
                sysUserService.addWxUser(wxUser);
            } else {
                user = sysUserService.apiLogin(MD5Utils.sign(openId));
            }
            if (user != null) {
                return Message.success()
                        .addData("data", user)
                        .addData("openId", MD5Utils.sign(openId));
            } else {
                throw new UserException("未知用户");
            }
        } catch (IOException | HttpException e) {
            throw new HttpException("请求失败: " + e.getMessage(), e);
        }
    }

    @RequestMapping("captcha")
    public Message message(@RequestParam("username") String username) throws UserException {
        return Message.success().addData("data", msgService.send(username));
    }
}
